<template>
  <div class="user flex-col pd-2">
    <div class="user-title mb-2">
      <el-button type="primary" @click="addUsers">添加用户</el-button>
    </div>
    <div class="userList">
      <el-table :data="userList" style="width: 100%">
        <el-table-column type="index" label="id"> </el-table-column>
        <el-table-column prop="username" label="用户名" min-width="180" show-overflow-tooltip>
          <template slot-scope="{ row, $index }">
            <div v-if="!row.isModified">
              {{ row.username }}
            </div>
            <el-form :ref="'usernameForm' + $index" label-width="0px" v-else :model="row" class="user-form">
              <el-form-item prop="username" :rules="userRules.USER_RULES.USERNAME">
                <el-input v-model="row.username" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column prop="password" label="密码" min-width="180" show-overflow-tooltip>
          <template slot-scope="{ row, $index }">
            <div v-if="!row.isModified">
              {{ row.password }}
            </div>
            <el-form :ref="'passwordForm' + $index" label-width="0px" v-else :model="row" class="user-form">
              <el-form-item prop="password" :rules="userRules.USER_RULES.PASSWORD">
                <el-input v-model="row.password" placeholder="请输入内容"></el-input>
              </el-form-item>
            </el-form>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100" header-align="center">
          <template slot-scope="{row, $index}">
            <div v-if="!row.isModified" class="space-around icon-box">
              <svg-icon @click="deleteUser(row, $index)" name='delete' :size="22"></svg-icon>
              <svg-icon @click="editUser(row)" name='edit' :size="22"></svg-icon>
            </div>
            <div v-else class="space-around icon-box">
              <svg-icon @click="beforeConfirm(row, $index)" name='confirm' :size="22"></svg-icon>
              <svg-icon @click="cancel(row, $index)" name='cancel' :size="22"></svg-icon>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
import { USER } from '../../global/constant'
import { UserApi, LoginApi } from "../../global/api";
export default {
  name: "user",
  data() {
    return {
      userApi: new UserApi(),
      loginApi: new LoginApi(),
      userList: [],
      userRules: USER
    };
  },
  computed: {
    editedStatus() {
      return this.userList.filter(user => user.isModified).length
    }
  },
  mounted() {
  },
  methods: {
    addUsers() {
      this.userList.push({
        username: '',
        password: '',
        isModified: true,
        isEdited: false
      })
    },
    async getUsersList() {
      const res = await this.userApi.getUsers();
      if(res.code === 200 && res.data?.length) {
        this.userList = res.data;
        this.userList.forEach(item => {
          this.$set(item, 'isModified', false)
          this.$set(item, 'isEdited', false)
        })
      }
    },
    async deleteUser(row, index) {
      const res = await this.userApi.deleteUser({id: row._id});
      if (res.code === 200) {
        this.userList.splice(index, 1)
      }
    },
    editUser(row) {
      row.intialPassword = row.password
      row.intialUsername = row.username
      row.isModified = true
      row.isEdited = true
    },
    async beforeConfirm(row, index) {
      try { 
        const isValids = await Promise.all([this.promiseValidate('usernameForm'+index), this.promiseValidate('passwordForm'+index)])
        if(isValids.every(item => item)) {
          this.confirm(row)
        }
      } catch(error) {
        console.log(error);
      }
    },
    async confirm(row) {
      const { _id, username, password } = row
      let res = {}
      if(row.isEdited) {
        res = await this.userApi.editUser({id: _id, username, password})
      } else {
        res = await this.loginApi.signup({ username, password })
      }
      if(res.code === 200) {
        row.isModified = false
        if(!this.editedStatus) {
          this.getUsersList()
        }
      }
    },
    promiseValidate(key) {
      return new Promise((resolve, reject) => {
        try {
          this.$refs[key].validate(isValid => {
            resolve(isValid)
          })
        } catch(error) {
          reject(error)
        }
      })
    },
    cancel(row, index) {
      if(row.isEdited) {
        row.password = row.intialPassword
        row.username = row.intialUsername
        row.isModified = false
      } else {
        this.userList.splice(index, 1)
      }
    }
  },
  created() {
    this.getUsersList();
  },
};
</script>

<style lang="less" scoped>
.user {
  &-form {
    .el-form-item {
      margin-bottom: 0;
    }
  }
  .icon-box {
    display: flex;
    color: rgba(0, 0, 0, .3);
    opacity: 0;
    transition: .8s linear;
    &:hover {
      color: #000;
    }
  }
  .el-table__body tr:hover{
    .icon-box{
      opacity: 1;
    }
  }
}

</style>
